package com.xiaoma.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: ThreadPoolFactory </p>
 * <p>Description：描述 </p>
 * <p>Package:com.xiaoma.factory </p>
 * Copyright: Copyright(c) 2020  All Rights Reserved Company:  Software: AIC Date: 2021/1/17 21:01
 *
 * @author maj
 * @version 1.0.0
 */
public class ThreadPoolFactory {

  private static int corePoolSize = 10;
  private static int maximumPoolSize = 15;
  private static long keepAliveTime = 4;
  private volatile static ThreadPoolExecutor threadPoolFactory=null;

  private ThreadPoolFactory(){}

  private static ThreadPoolExecutor getPool(){
    if(threadPoolFactory==null){
      synchronized (ThreadPoolFactory.class){
        if(threadPoolFactory==null){
          threadPoolFactory=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
              new ArrayBlockingQueue<Runnable>(100), new ThreadPoolExecutor.DiscardOldestPolicy());
          threadPoolFactory.allowCoreThreadTimeOut(true);//true，允许回收核心线程。

        }
      }
    }

    return threadPoolFactory;
  }

  public static void main(String[] args) {
    ThreadPoolExecutor pool = getPool();
    for (int i = 0; i < 6; i++) {
      pool.execute(new Runnable() {
        @Override
        public void run() {
          System.out.println("sdfsdf");
        }
      });
    }

    try {
      Thread.sleep(60000);
      System.out.println("sleep end ..");

    } catch (InterruptedException e) {
      e.printStackTrace();
    }


    pool.execute(new Runnable() {
      @Override
      public void run() {
        System.out.println("end.....");
      }
    });

  }

}
